package weibo.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.microedition.io.HttpConnection;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.w3c.dom.Document;

import weibo.model.WeiboException;

public class Response
{
    private int statusCode;
    private Document responseAsDocument = null;
    private String responseAsString = null;
    private InputStream is;
    private HttpConnection con;
    private boolean streamConsumed = false;

    public Response()  {}
    
    public Response(HttpConnection con) throws IOException {
        this.con = con;
        this.statusCode = con.getResponseCode();
        is = con.openInputStream();
    }

    Response(String content) {
        this.responseAsString = content;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getResponseHeader(String name) throws IOException {
    	if (con != null)
    		return con.getHeaderField(name);
    	else
    		return null;
    }

    public InputStream asStream() {
        if(streamConsumed){
            throw new IllegalStateException("Stream has already been consumed.");
        }
        return is;
    }

    /**
     * Returns the response body as string.<br>
     * Disconnects the internal HttpURLConnection silently.
     * @return response body
     * @throws WeiboException
     */
    public String asString() throws WeiboException{
        if(null == responseAsString){
            try {
                InputStream stream = asStream();
                if (null == stream) {
                    return null;
                }
                
                InputStreamReader br = new InputStreamReader(stream, "UTF-8");
                StringBuffer buf = new StringBuffer();
                //int offset = 0;
                char[] buffer = new char[250];
                while (br.read(buffer)!=-1) {
                    buf.append(buffer).append("\n");
                }
                this.responseAsString = buf.toString();

                stream.close();
                con.close();
                streamConsumed = true;
            } catch (NullPointerException npe) {
                // don't remember in which case npe can be thrown
                //throw new WeiboException(npe.getMessage(), npe);
            } catch (IOException ioe) {
                //throw new WeiboException(ioe.getMessage(), ioe);
            }
        }
        return responseAsString;
    }

    public JSONObject asJSONObject() throws WeiboException {
    	try {
            return new JSONObject(asString());
        } catch (JSONException jsone) {
            throw new WeiboException(jsone.getMessage() + ":" + this.responseAsString);
        }
    }

    public JSONArray asJSONArray() throws JSONException, WeiboException {
		return  new JSONArray(asString());
    }

    public InputStreamReader asReader() {
        try {
            return new InputStreamReader(is, "UTF-8");
        } catch (java.io.UnsupportedEncodingException uee) {
            return new InputStreamReader(is);
        }
    }

    public void disconnect(){
        try {
			con.close();
		} catch (IOException e) {}
    }

    public String toString() {
        if(null != responseAsString){
            return responseAsString;
        }
        return "Response{" +
                "statusCode=" + statusCode +
                ", response=" + responseAsDocument +
                ", responseString='" + responseAsString + '\'' +
                ", is=" + is +
                ", con=" + con +
                '}';
    }

	public String getResponseAsString() {
		return responseAsString;
	}

	public void setResponseAsString(String responseAsString) {
		this.responseAsString = responseAsString;
	}

	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;
	}
    
}